﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
namespace test
{
    public partial class upload : System.Web.UI.Page
    {
protected void btnAttach_Click(object sender, System.EventArgs e)
  {
   // Save the attached file to fileName variable
   string fileName = FileUpload.PostedFile.FileName;
   // If the counter is null then create one with default value equal to 0
   if(ViewState["i"] == null)
   {
    ViewState["i"]= 0;
   }
   // Check if a file is selected 
   if(fileName != null || fileName != string.Empty)
   {
    // Add  it to the collection
    ListBox1.Items.Add(FileUpload.PostedFile.FileName);
    // Save an index for each selected file
    int i = Convert.ToInt32(ViewState["i"]);
    // Save the fileupload control into a different session
    Session["myupload" + i] = FileUpload;
    // Increment the counter
    i++;
    // Set the ViewSate to the latest counter value.
    ViewState["i"] = i;
    
   }
  }
protected void btnUpload_Click(object sender, System.EventArgs e)
  {
   int sessionCount = Session.Count;
   
   
   ///int sessionCount = Convert.ToInt32(ViewState["i"]);
   for( int i =sessionCount-1;i>=0;i--)
   {
    if(sessionCount <= 3)
    {
     HtmlInputFile hif = (HtmlInputFile)Session["myupload" + i];
     if(hif.PostedFile.ContentLength <= 500000)
     {
      string storePath = Server.MapPath("~") + "/MultipleUpload";
      if(!Directory.Exists(storePath))
       Directory.CreateDirectory(storePath);
      hif.PostedFile.SaveAs(storePath  + "/" +  Path.GetFileName(hif.PostedFile.FileName));
      Label1.Text = "Your Files are uploaded successfully";
      ListBox1.Items.Clear();
     }
     else
     Label1.Text = "An error occured";
    }
    else
     Label1.Text = "You have exceeded the maximum number of files to be uploaded (3)";
     
   }
   Session.RemoveAll();
  }
protected void btnDelete_Click(object sender, System.EventArgs e)
  {
   if(ListBox1.SelectedIndex > -1)
   {
    int uploadedFileIndex = ListBox1.SelectedIndex;
    Session.Remove("myupload" + uploadedFileIndex);
    ListBox1.Items.Remove(ListBox1.SelectedValue);
   }
  }

    }
}
